using System;
using Headspring.Training.Domain.Model;
using Headspring.Training.Domain.Services;
using Headspring.Training.WebUI.Views;

namespace Headspring.Training.WebUI.Presenters
{
	public class WorkOrderPresenter
	{
		private readonly IEmployeeRepository _employeeRepository;
		private readonly IWorkOrderRepository _workOrderRepository;
		private readonly IWorkOrderBuilder _workOrderBuilder;
		private readonly IUserSession _session;
		private readonly IWorkflowFacilitator _workflowFacilitator;
		private readonly IWorkflowCoordinator _workflowCoordinator;

		public WorkOrderPresenter(IEmployeeRepository employeeRepository, IWorkOrderRepository workOrderRepository,
		                          IWorkOrderBuilder workOrderBuilder, IUserSession session,
		                          IWorkflowFacilitator workflowFacilitator, IWorkflowCoordinator workflowCoordinator)
		{
			_employeeRepository = employeeRepository;
			_workOrderRepository = workOrderRepository;
			_workOrderBuilder = workOrderBuilder;
			_session = session;
			_workflowFacilitator = workflowFacilitator;
			_workflowCoordinator = workflowCoordinator;
		}

		public void Execute(ISingleWorkOrderView view)
		{
			view.CurrentUser = _session.GetCurrentUser();
			view.AllEmployees = _employeeRepository.GetAllEmployees();
			EditMode mode = view.GetEditMode();
			WorkOrder workOrder = null;
			if (mode == EditMode.New)
			{
				workOrder = _workOrderBuilder.CreateNewWorkOrder(_session.GetCurrentUser());
			}
			else if (mode == EditMode.Edit)
			{
				string woNumber = view.GetWorkOrderNumber();
				workOrder = _workOrderRepository.GetWorkOrder(woNumber);
			}

			view.WorkOrder = workOrder;
			IStateCommand[] validCommands = _workflowFacilitator.GetValidStateCommands(workOrder, _session.GetCurrentUser());
			view.SetCommandsToShow(validCommands);
		}

		public void ExecuteCommand(ISingleWorkOrderView view, string commandName)
		{
			WorkOrder workOrder = view.WorkOrder;

			IStateCommand[] commands = _workflowFacilitator.GetValidStateCommands(workOrder, _session.GetCurrentUser());
			IStateCommand matchingCommand =
				Array.Find(commands, delegate(IStateCommand obj) { return obj.Matches(commandName); });

			matchingCommand.Execute(_workflowCoordinator);
		}

		public bool UserCanChangeAssignee(ISingleWorkOrderView view)
		{
			//does this really belong here or is this log misplaced?
			if(view.WorkOrder.Status != WorkOrderStatus.Draft)
			{
				return false;
			}

			return true;
		}
	}
}